import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/widgets/goods_config/goods_detail/detail_page.dart';
import 'package:xws/widgets/refresh_widget/refresh_load_view.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'my_goods_item.dart';

/// 获得的物品
class MyGet extends StatefulWidget {
  const MyGet({Key? key}) : super(key: key);

  @override
  _MyGetState createState() => _MyGetState();
}

class _MyGetState extends State<MyGet> with SafeState<MyGet> {
  late RefreshViewController<GoodsObj> _viewController;

  @override
  void initState() {
    super.initState();
    _viewController = RefreshViewController<GoodsObj>();
  }

  @override
  void dispose() {
    _viewController.dispose();
    super.dispose();
  }

  /// 详情
  Future<void> _detail(int index, GoodsObj g) async {
    await push<bool>(context, DetailPage(goods: g, index: index));

    if (!g.favoriteFlag) _viewController.remove(index);
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '我获得的',
      body: RefreshLoadView<GoodsObj>(
        viewController: _viewController,
        type: ViewType.grid,
        itemBuilder: (int index, GoodsObj g) => MyGoodsItem(
          index: index,
          goods: g,
          onTap: () => _detail(index, g),
        ),
        padding: const EdgeInsets.all(20),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          crossAxisCount: 2,
          childAspectRatio: 0.9,
        ),
        onRefresh: (_, __) async {
          return getGoodsList(
            pageNum: 1,
            searchType: GoodsSearchType.GET,
          );
        },
        onLoad: (int page, __) async {
          return getGoodsList(
            pageNum: page,
            searchType: GoodsSearchType.GET,
          );
        },
      ),
    );
  }
}
